<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div class="page_body">
      <!-- 按钮操作栏 -->
      <BtnRender :render="renderBtnsBar" />
      <el-row>
        <SkusTable
          ref="skusTable"
          showSelectCol
          showActionCol
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="tableInfo.list"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :pageSizes="pageSizes"
          :pagination="pagination"
          :total="pagination.total"
          :selectionChange="handleSelectionChange"
          :actionRender="renderTableBtnAction"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
        />
      </el-row>
      <!-- 表尾字段 -->
      <FooterFields v-if="recordNo" :footerFields="footerFields" />
    </div>
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
    />
    <!-- 关联商品弹框 -->
    <GoodsLinkedDialog
      :visible.sync="goodsLinked.visible"
      @getLinkedRows="getTableDataByGoodsLinked"
    />
    <!-- 新增自定义属性弹框 -->
    <AddAttrDialog
      :visible.sync="addAttr.visible"
      :dataSource="tableInfo.selection"
      :allTableData="tableInfo.list"
      @getAddAttrs="getTableDataByAddAttrs"
    />
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import GoodsLinkedDialog from './components/GoodsLinkedDialog';
import AddAttrDialog from './components/AddAttrDialog';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { generateUuid, createExcelByExport, isResponseSuccess, setAuthBtnId } from '@/utils/bizUtils';
import skusPage from '@/mixins/commodity/skusPage';
import { TABLE_COLUMNS } from './constants/home'
import {
  getSpuBasicInfoListService,
  commitSpuDataService,
  addCustomAttrService,
  exportSpuDataService,
  getRecordInfoForEditService
} from '@/api/commodity/commodityInfoEdit/basicAttrBatchEdit';
export default {
  mixins: [skusPage],
  components: {
    BtnRender,
    SkusTable,
    FooterFields,
    SeniorLinkedDialog,
    GoodsLinkedDialog,
    AddAttrDialog
  },
  data () {
    return {
      formData: {},
      // 表格信息
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      btnLoading: {
        export: false,
        submit: false
      },
      footerFields: {},
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SPU编码', prop: 'spuNo', type: 'textarea' }],
        dataSource: [{ spuNo: '' }]
      },
      goodsLinked: {
        visible: false,
      },
      linkedSpuNos: [], // 已关联商品编码集合（高级关联、关联商品的并集）
      addAttr: {
        visible: false
      },
      recordNo: '' // 单据号
    }
  },
  computed: {
    hasNoSelection() {
      return this.tableInfo.selection.length === 0;
    },
    isNullTable() {
      return this.tableInfo.list.length === 0;
    },
    updateParamList() {
      const updateParamList = this.tableInfo.list.map(item =>
        item.valueType == '04' ? ({ ...item, valueNameUpdate: item.valueNameUpdate.join(',') }) : item
      )
       return updateParamList
    },
    pageTitle() {
      if (this.recordNo) return '修改基本信息-表单修改页面'
      return '修改基本信息'
    },
  },
  mounted() {
    this.loadInitDataInMounted()
  },
  methods: {
    // jsx-render渲染按钮操作栏
    renderBtnsBar(h) {
      const basicBtns = [
        { label: '高级关联', method: this.handleSeniorLinked, icon: 'el-icon-link', hasAuth: true },
        { label: '关联商品', method: this.handleGoodsLinked, hasAuth: true },
        { label: '导出模板', method: this.handleExportTemplate, loading: this.btnLoading.export, disabled: this.isNullTable },
        {
          label: '导入模板',
          action: 'sysback/update/product/spuBasicInfo/importExcel',
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: state => { this.tableInfo.loading = state }
        },
        { label: '新增自定义属性', method: this.handleAddAttr, disabled: this.hasNoSelection },
        { label: '删除自定义属性', method: this.handleDeleteAttr, disabled: this.hasNoSelection },
        { label: '提交', method: this.handleSubmit, loading: this.btnLoading.submit, disabled: this.isNullTable },
      ]
      if (this.recordNo) { // 表单修改页面展示返回按钮，菜单页面无需展示
        basicBtns.push({ label: '返回', method: this.handleGoBack });
      }
      const btnList = basicBtns.map(item => ({ ...item, size: 'large' }))
      return getBtnsBar(h, btnList, this.showBtn);
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction(h, { row }) {
      const cancelBtn = { label: '取消关联', method: this.handleCancelLink };
      const actionList = [cancelBtn];
      return getTableAction({ h, row, actionList });
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.setTableColumns(TABLE_COLUMNS)
      this.recordNo = this.$route?.query?.recordNo ?? '';
      if (this.recordNo) {
        this.setRecordInfo(this.recordNo)
      }
    },
    // 设置单据信息
    async setRecordInfo (recordNo) {
      const data = { recordNo }
      const target = '.page_body'
      const res = await getRecordInfoForEditService(data, target)
      if (res?.retData) {
        this.tableInfo.list = this.getFormatTableData(res.retData.spuBasicInfoVoList)
        const spuNos = this.tableInfo.list.map(item => item.spuNo).filter(item => item)
        this.linkedSpuNos = [...new Set(spuNos)]
        this.footerFields = res.retData
      }
    },
    // 返回
    handleGoBack() {
      this.$router.push({ name: 'chageFromManageList' })
    },
    // 导出模板
    async handleExportTemplate() {
      const data = this.updateParamList
      const loadingFn = state => { this.btnLoading.export = state };
      const res = await exportSpuDataService(data, loadingFn);
      createExcelByExport({ res, excelTitle: `批量修改基本属性_${generateUuid()}` });
    },
    // 导入成功
    handleUploadSuccess(res) {
      this.tableInfo.list = this.getFormatTableData(res.retData)
    },
    // 提交
    async handleSubmit() {
      const data = {
        updateParamList: this.updateParamList,
        recordNo: this.recordNo
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitSpuDataService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        this.$router.push({ name: 'chageFromManageList' })
      }
    },
    // 表格勾选
    handleSelectionChange(list) {
      this.tableInfo.selection = list;
    },
    // 高级关联
    handleSeniorLinked() {
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleGoodsLinked() {
      this.goodsLinked.visible = true
    },
    // 新增自定义属性
    handleAddAttr() {
      this.addAttr.visible = true
    },
    // 删除
    handleDeleteAttr() {
      this.$confirm('确定要删除吗？', '删除', {
        type: 'warning',
      }).then(() => {
        const { validateCannotDelete, deleteRelRows, cancelLinkSpuNo } = this.getBatchDeleteExecutors()
        const cannotNext = validateCannotDelete()
        if (cannotNext) return
        deleteRelRows()
        cancelLinkSpuNo()
        this.$message.success('删除成功')
      }).catch(() => {});
    },
    // 取消关联
    handleCancelLink(row) {
      const index = this.linkedSpuNos.findIndex(item => item.spuNo == row.spuNo)
      this.linkedSpuNos.splice(index, 1)
      this.tableInfo.list = this.tableInfo.list.filter(item => item.spuNo != row.spuNo)
      this.$message.success('取消关联成功')
    },
    // 获取表格数据 高级关联
    getTableDataBySeniorLinked(spuNos) {
      setAuthBtnId('高级关联')
      // this.linkedSpuNos = [...new Set([...this.linkedSpuNos, ...spuNos])]
      this.setTableData(spuNos)
    },
    // 获取表格数据 关联商品
    getTableDataByGoodsLinked(list) {
      setAuthBtnId('关联商品')
      const spuNos = list.map(item => item.spuNo)
      // this.linkedSpuNos = [...new Set([...this.linkedSpuNos, ...spuNos])]
      this.setTableData(spuNos)
    },
    // 获取表格数据 新增自定义属性
    async getTableDataByAddAttrs(customAttrNames) {
      const data = {
        updateParamList: this.updateParamList,
        selSpuNos: this.tableInfo.selection.map(item => item.spuNo),
        customAttrNames
      }
      const loadingFn = state => { this.tableInfo.loading = state }
      const res = await addCustomAttrService(data, loadingFn)
      if (res?.retData) {
        this.tableInfo.list = res.retData
      }
    },
    // 批量删除自定义属性
    getBatchDeleteExecutors() {
      let validateCannotDelete = () => {
        const isAllCustomAttrs = this.tableInfo.selection.every(item => !item.attrUuid)
        if (!isAllCustomAttrs) this.$message.warning('存在非规格属性，请取消勾选后再进行删除')
        return !isAllCustomAttrs
      }
      let deleteRelRows = () => {
        this.tableInfo.list = this.tableInfo.list.filter(
          item => !this.tableInfo.selection
            .map(item => item.uuid)
            .filter(item => item)
            .includes(item.uuid)
        );
      }
      let cancelLinkSpuNo = () => {
        this.tableInfo.selection.forEach(item => {
          const target = this.tableInfo.list.find(el => el.spuNo == item.spuNo)
          if (!target) {
            const index = this.linkedSpuNos.findIndex(spuNo => item.spuNo == spuNo)
            this.linkedSpuNos.splice(index, 1)
          }
        })
      }
      const executors = { validateCannotDelete, deleteRelRows, cancelLinkSpuNo }
      validateCannotDelete = null
      deleteRelRows = null
      cancelLinkSpuNo = null
      return executors
    },
    // 设置表格数据
    async setTableData(spuNos) {
      const data = { spuNos }
      const loadingFn = state => { this.tableInfo.loading = state }
      const res = await getSpuBasicInfoListService(data, loadingFn)
      if (res?.retData) {
        const filterList = this.tableInfo.list.filter(item => !spuNos.includes(item.spuNo))
        this.tableInfo.list = this.getFormatTableData([...filterList, ...res.retData])
      }
    },
    // 获取格式化的表格数据
    getFormatTableData(list = []) {
      const newList = list.map(item => {
        if (item.valueType == '04') {
          const valueNameUpdate = Array.isArray(item.valueNameUpdate)
            ? item.valueNameUpdate
            : item.valueNameUpdate.split(',').filter(item => item)
          return { ...item, valueNameUpdate }
        }
        return item
      })
      return newList
    },
    // 获取渲染组件
    getElCompFnList() {
      let getSelOptListMaps = (selOptList, valueNameUpdate) => {
        const selOptListMaps = new Map()
        selOptList.forEach(item => {
          selOptListMaps.set(item.optionHtml, item.optionValue)
        })
        const valueUuid = selOptListMaps.get(valueNameUpdate)
        return valueUuid
      }
      let selectChangeEvt = (row, valueType) => {
        if (!['03', '04'].includes(valueType)) return
        const nameList = typeof row.valueNameUpdate == 'string' ? [row.valueNameUpdate] : row.valueNameUpdate
        const valueUuidUpdate = nameList.reduce((uuids, name) => {
          const valueUuid = getSelOptListMaps(row.selOptList, name)
          valueUuid && uuids.push(valueUuid)
          return uuids
        }, [])
        row.valueUuidUpdate = valueUuidUpdate.join(',')
      }
      // valueType - 03：下拉单选框；04：下拉多选框；05：下拉单选框/文本框
      let getSelectCol = (valueType) => {
        return (h, row) => {
          const isMultiple = valueType == '04'
          return (<el-select
            v-model={ row.valueNameUpdate }
            placeholder="请选择"
            multiple={ isMultiple }
            collapse-tags={ isMultiple }
            filterable={ valueType == '05' }
            allow-create={ valueType == '05' }
            default-first-option={ valueType == '05' }
            onChange={() => { selectChangeEvt(row, valueType) }}
          >{
            (row.selOptList ?? []).map(item =>
              <el-option
                key={item.optionValue}
                label={item.optionHtml}
                value={item.optionHtml}
              />
            )
          }</el-select>)
        }
      }
      let getInputCol = (h, row) => {
        return <el-input v-model={row.valueNameUpdate} />
      }
      const comps = { getSelectCol, getInputCol }
      getSelectCol = null
      getInputCol = null
      return comps
    },
    // 设置表格表列
    setTableColumns(columns) {
      const { getSelectCol, getInputCol } = this.getElCompFnList()
      const compMaps = {
        '01': getInputCol,
        '03': getSelectCol('03'),
        '04': getSelectCol('04'),
        '05': getSelectCol('05')
      }
      const renderAttrValCol = {
        title: '属性值-现值',
        width: 160,
        render: (h, { row }) => {
          const getCompFn = compMaps[row.valueType]
          return (getCompFn ? getCompFn(h, row) : <span></span>)
        }
      }
      this.tableInfo.columns = [...columns, renderAttrValCol]
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-tag--info {
  max-width: 65px;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
  .el-icon-close {
    position: absolute;
    left: 51px;
    top: 4px;
  }
}
</style>
